package com.leap.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leap.entity.Account;
import com.leap.entity.Comment;
import com.leap.entity.dto.CommentDTO;
import com.leap.entity.vo.CommentChildVO;
import com.leap.mapper.CommentMapper;
import com.leap.service.AccountService;
import com.leap.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

@Service
@Slf4j
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private AccountService accountService;

    @Override
    public List<CommentChildVO> selectChildListById(Long commentId, List<Long> interactComments) {

        List<Comment> comments = commentMapper.selectChildrenById(commentId);
        List<CommentChildVO> list = comments.stream().map(item -> {
            Account account = accountService.getById(item.getAccountId());

            return CommentChildVO.builder()
                    .id(item.getId())
                    .avatar(account.getAvatar())
                    .nickname(account.getName())
                    .content(item.getContent())
                    .likeCount(item.getLikeCount())
                    .isLiked(interactComments.contains(item.getId()) ? 1 : 0)
                    .createTime(item.getCreateTime())
                    .build();
        }).toList();

        return list;
    }

    @Override
    public Comment saveDTO(CommentDTO commentDTO,Long accountId) {

        int x = 1;
        if (commentDTO.getAnswerId() == 0){
            x = 0;
        }
        Comment comment = Comment.builder()
                .accountId(accountId)
                .answerId(commentDTO.getAnswerId())
                .channelId(commentDTO.getChannelId())
                .content(commentDTO.getContent())
                .type(x)
                .likeCount(0)
                .build();
        this.saveOrUpdate(comment);

        return comment;
    }

    @Override
    public void deleteDTO(Long commentId) {
        this.removeById(commentId);
    }

    @Override
    public Long getSumByChannelId(int channelId) {
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getChannelId, channelId);
        wrapper.eq(Comment::getType, 0);

        return this.count(wrapper);
    }
}
